package com.sjj.shopping.webSocket;

import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.thymeleaf.spring5.context.SpringContextUtils;
import service.UserService;

import javax.annotation.PostConstruct;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * className:WebSocketServer
 * Package:com.sjj.shopping.webSocket
 * Description:
 *
 * @Date: 2022/8/14 21:07
 * @Auther: wssky19890629@163.com
 */

@ServerEndpoint("/websocket/{myUserId}/{hisUserId}")
@Component
@SuppressWarnings("all")
public class WebSocketServer {
    @Reference
    private static UserService staticuserService;

    @Reference
    private  UserService userService;

    @PostConstruct
    public void init(){
        staticuserService=userService;
    }


    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet= new CopyOnWriteArraySet<>();
    private Session session;

    private String myUserId;
    private String hisUserId;


    @OnOpen
    public void onOpen(Session session, @PathParam("myUserId") String myUserId,@PathParam("hisUserId") String hisUserId){
        //赋值
        this.session=session;
        this.myUserId=myUserId;
        this.hisUserId=hisUserId;

        //将当前连接放入set
        webSocketSet.add(this);

        //取出堆积在redis中的消息
        List<String> msgFromRedis = staticuserService.getMsgFromRedis(myUserId, hisUserId);
        msgFromRedis.stream().forEach(a->{
            sendRedisInfo(myUserId,hisUserId,a);
        });
    }



    private   void sendMessage(String message) throws IOException {
        //向游览器发送消息
        this.session.getBasicRemote().sendText(message);
    }

    public  void sendRedisInfo( @PathVariable("myUserId") String myUserId, @PathVariable("hisUserId") String hisUserId,String message){
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        try {
            this.sendMessage(dateFormat.format(date) + "  " + hisUserId + ":" + message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void sendInfo( @PathVariable("myUserId") String myUserId, @PathVariable("hisUserId") String hisUserId,String message){

        //对方是否在线
        int status=0;

        for(WebSocketServer item:webSocketSet){

            //给我自己发消息
            if(hisUserId.equals(item.hisUserId) && myUserId.equals(item.myUserId) ){
                try {
                    Date date = new Date();
                    SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
                    item.sendMessage(dateFormat.format(date)+"  "+myUserId+":"+message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            //给对方发消息
            if(hisUserId.equals(item.myUserId) && myUserId.equals(item.hisUserId) ){
                //对方在线
                status++;
                try {
                    Date date = new Date();
                    SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
                    item.sendMessage(dateFormat.format(date)+"  "+myUserId+":"+message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        //对方不在线，存到reids中
        if(status==0){
            staticuserService.setMsgtoRedis(myUserId, hisUserId, message);
        }
    }
}
